<?php
/**
 * Created by PhpStorm.
 * User: 554665488
 * Date: 2018-6-24
 * Time: 16:02
 * @description:服务端
 * @Author: yfl
 * @QQ 554665488
 */
$server = new Swoole\Server('0.0.0.0', 9501, SWOOLE_PROCESS, SWOOLE_SOCK_TCP);

//配置eof协议分包
//$server->set([
//
//    'worker_num' => 2, //设置进程
//    'open_eof_check' => true, //打开EOF检测
//    'package_eof' => "\r\n", //设置EOF
//    'open_eof_split' => true //自动进行边界分割
//]);

//固定包头跟包体协议
$server->set([
    'open_length_check' => true,
    'package_length_type' => 'N',
    'package_length_offset' => 0, //计算总长度
    'package_body_offset' => 4,//包体位置
    'package_max_length' => 1024 * 1024 //总的请求数据大小字节为单位
]);

$server->on('connect', function ($serv, $fd) {
//    echo "有新的客户端连接，连接标识为$fd" . PHP_EOL;
});

$server->on('receive', function ($serv, $fd, $from_id, $data) {
    $len = unpack('N', $data)[1];
    $data = substr($data, -$len);
    $pack = pack('N',strlen("服务器给你发送消息了: " . $data))."服务器给你发送消息了: " . $data;
    for ($i = 0; $i < 5; $i++) {
        $serv->send($fd,  $pack);
    }


});

$server->on('close', function ($serv, $fd) {
//    echo "编号为{$fd}的客户端已经关闭." . PHP_EOL;
});


$server->start();
